#pragma once

#include "ClientConnection.hpp"

namespace network {

    class TcpClient : public ClientConnection {

    public:

        TcpClient() { initHandler(); }

        explicit TcpClient(Reactor *reactor) : ClientConnection(Socket::createSocket(), false, reactor) {
            initHandler();
        }

    private:

        // 初始化注册到Reactor模型上
        void initHandler();

        // 客户端回调
        void clientHandler(int, EventType, void *);

    };

    void TcpClient::clientHandler(int fd, EventType event_type, void *context) {
        try {
            if (event_type == EventType::Read) {
                clientRecv();
            }
            else if (event_type == EventType::Write) {
                clientSend();
            }
            else if (event_type == EventType::Close) {
                clientClose();
            }
        }
        catch (const std::exception &e) {}
    }

    void TcpClient::initHandler() {
        reactor_->registerHandler(getFd(), EventType::Read,
                                  std::bind(&TcpClient::clientHandler, this, std::placeholders::_1, std::placeholders::_2,
                                       std::placeholders::_3),
                                  nullptr);
    }

}
